<template>
  <t-dialog
    v-model:visible="visible"
    :close-on-esc-keydown="false"
    :close-on-overlay-click="false"
    :header="title"
    :width="406"
    :confirm-loading="loading"
    class="common-dialog"
    @confirm="handleConfirm"
    @close="handleClose"
  >
    <div class="form-content">
      <t-form ref="formRef" :rules="FORM_RULES" :data="formData" :colon="true" :label-width="120" label-align="left">
        <form-item v-for="(item, index) in list" :key="index" :form-data="formData" :data="item"></form-item>
      </t-form>
    </div>
  </t-dialog>
</template>

<script setup lang="ts">
import _ from 'lodash';
import { tryit } from 'radash';
import { FormInstanceFunctions, MessagePlugin } from 'tdesign-vue-next';
import { nextTick, PropType, ref } from 'vue';

import mockApi from '@/api/mock';
import { PostData, ResultItem } from '@/api/model/mockModel';
import { SUCCESS_CODE } from '@/constants';
import { requestCancel } from '@/utils/request';

import { FORM_RULES, INIT_DATA, list } from '../datas/edit';

const props = defineProps({
  title: {
    type: String as any,
    default: '弹框',
  },
  data: {
    type: Object as PropType<ResultItem>,
    default: () => {
      return {};
    },
  },
});

const emits = defineEmits(['sure']);

const visible = ref(false);
const formRef = ref<FormInstanceFunctions>();
const formData = ref<PostData>(_.cloneDeep(INIT_DATA));
const loading = ref(false);

const close = () => {
  visible.value = false;
};

const open = async () => {
  visible.value = true;
  await nextTick();
  await setData();
};

// 设置数据
const setData = async () => {
  formRef.value.reset();

  if (props.data?.id) {
    formData.value = _.cloneDeep(props.data);
  } else {
    formData.value = _.cloneDeep(INIT_DATA);
  }
};

// 确认回调
const handleConfirm = async () => {
  const validateRes = await formRef.value.validate();

  if (validateRes === true) {
    loading.value = true;

    const postData: PostData = { ...formData.value };
    const id = props.data?.id;
    const api = id ? mockApi.update : mockApi.create;

    if (id) postData.id = id;

    const [err, res] = await tryit(api)(postData);

    if (!err && res.code === SUCCESS_CODE) {
      await MessagePlugin.success('操作成功');
      close();
      emits('sure');
    }

    loading.value = false;
  }
};

// 取消回调
const handleClose = () => {
  const api = props.data?.id ? mockApi.api.update : mockApi.api.create;
  if (loading.value) {
    requestCancel(api, 'post');
    loading.value = false;
  }
};

defineExpose({ close, open });
</script>

<style lang="less" scoped></style>
